package org.support.small.mallms.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.util.StringUtils;

import java.util.Locale;
import java.util.Objects;

@Slf4j
public class I18NUtils {
    public static String getMessage(String... codeArr) {
        if (Objects.isNull(codeArr) || codeArr.length == 0) {
            return null;
        }
        // 当前请求的语言环境
        Locale locale = LocaleContextHolder.getLocale();
        MessageSource messageSource = SpringUtils.getBean("messageSource", MessageSource.class);
        for (String code : codeArr) {
            try {
                String message = messageSource.getMessage(code, null, locale);
                if (StringUtils.hasText(message)) {
                    return message;
                }
            } catch (NoSuchMessageException e) {
                log.error("{}:{}", code, e.getMessage());
            }
        }
        return codeArr[0];
    }
}
